package maintain

import (
	"fmt"
	"io/ioutil"
	"iot-base/common/logger"
	"iot-base/common/maintain"
	"iot-base/common/notify"
	"iot-base/common/webapi"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"github.com/gin-gonic/gin"
)

var isInUpgrading = false

func initUpgrade(r *gin.RouterGroup) {
	r.POST("/upgrade/", func(c *gin.Context) {
		if isInUpgrading {
			webapi.SendError("last upgrade is not finished", webapi.ExecError, c)
			return
		}
		isInUpgrading = true
		var body map[string]string
		var filename string
		var password string
		err := c.ShouldBind(&body)
		if err == nil {
			filename, _ = body["file_name"]
			password, _ = body["password"]

		}
		if password == "" {
			password = "linaro"
		}

		if len(filename) == 0 {
			webapi.SendError(err.Error(), webapi.ExecError, c)
			isInUpgrading = false
			return
		}
		file, _ := exec.LookPath(os.Args[0])
		path, _ := filepath.Abs(file)
		dir := filepath.Dir(path)

		if strings.Contains(strings.ToLower(filename), "http") || strings.Contains(strings.ToLower(filename), "ftp") {
			if maintain.UpgradeByURLEx(filename, body["param"]) {
				webapi.SendOK(c)
			} else {
				webapi.SendError("upgrade error", webapi.ExecError, c)
			}
			return
		}
		scriptpath := "sudo " + dir + "/upgrade.sh"
		displayPath := filepath.Dir(dir)
		logger.SLog.Info("run upgrade------------------------", scriptpath, filename)
		pCmdrm := exec.Command("/bin/sh", "-c", "sudo rm -f "+displayPath+"/display.txt")
		pCmdrm.Run()
		pCmd := exec.Command("/bin/sh", "-c", scriptpath+" "+filename+" "+password)
		err = pCmd.Start()
		logger.SLog.Error("run result", err)

		if err != nil {
			webapi.SendError("run script error", webapi.ExecError, c)
		} else {
			webapi.SendOK(c)
		}

	})
	r.GET("/upgrade/", func(c *gin.Context) {
		file, _ := exec.LookPath(os.Args[0])
		path, _ := filepath.Abs(file)
		dir := filepath.Dir(path)
		updir := filepath.Dir(dir)
		displayPath := updir + "/display.txt"
		fmt.Println("**************", displayPath)
		f, err := ioutil.ReadFile(displayPath)
		if err != nil {
			webapi.SendError(err.Error(), webapi.ExecError, c)
		} else {
			webapi.SendResult(string(f), nil, c)
		}

	})
	r.POST("/upgradeEdges/:type", func(c *gin.Context) {
		utype := c.Param("type")
		var body map[string]string
		var filename string
		//var password string
		var param string
		var ids string
		err := c.ShouldBind(&body)
		if err == nil {
			filename, _ = body["file_name"]
			param, _ = body["param"]
			ids, _ = body["ids"]

		}
		if utype == "all" {
			notify.PubMsg(true, "upgrade_edges", &maintain.UpgradeCmd{
				URL:     filename,
				Param:   param,
				EdgeIDs: []string{"all"},
			})
		} else {
			notify.PubMsg(true, "upgrade_edges", &maintain.UpgradeCmd{
				URL:     filename,
				Param:   param,
				EdgeIDs: strings.Split(ids, ","),
			})
		}
		webapi.SendOK(c)
	})

}
